<template>
  <a-modal
    v-model:visible="visible"
    :width="845"
    :maskClosable="false"
    :title="'上传图片'"
  >
    <div class="own-multi-photo-upload">
      <div class="d-flex align-items-center mb-md">
        <span class="w-100 mr-md text-right">上传至文件夹</span>
        <a-select v-model:value="folderId" class="w-150">
          <a-select-option
            v-for="item in folders"
            :key="item.id"
            :value="item.id"
            >{{ item.folderName }}</a-select-option
          >
        </a-select>
      </div>
      <div class="d-flex align-items-center mb-md">
        <span class="w-100 mr-md text-right">上传图片</span>
        <a-button type="default" @click="chooseFile"> 本地上传 </a-button>
        <input
          type="file"
          style="display: none"
          ref="uploadInput"
          @change="fileChangeEvent"
          multiple
        />
      </div>
      <div class="file-wrapper" v-if="fileList.length > 0">
        <div class="image-box" v-for="(item, i) in fileList" :key="item.name">
          <!-- <div class="delete" @click="deleteImg(i)">
            <close-circle-filled style="color: red;"/>
          </div> -->
          <a-popover :title="null">
            <template #content>
              <div>
                <a-button type="text" @click="setVisible(true, i)">
                  <template #icon> <eye-outlined /> </template>预览</a-button
                >
                <a-button type="text" @click="openCropped(item, i)">
                  <template #icon> <scissor-outlined /> </template
                  >裁剪</a-button
                >
                <a-button type="text" @click="deleteImg(item.name)"
                  ><template #icon> <delete-outlined /> </template
                  >删除</a-button
                >
              </div>
            </template>
            <img :src="item.src" />
          </a-popover>
        </div>
      </div>
      <a-image-preview-group
        :preview="{
          visible: viewVisible,
          onVisibleChange: setVisible,
          current: viewCurrent,
        }"
      >
        <a-image
          :style="{ display: 'none' }"
          v-for="item in fileList"
          :key="item.name"
          :src="item.src"
        />
      </a-image-preview-group>
      <div class="d-flex" v-if="isUploadingFile">
        <div style="margin-left: 120px" class="flex-1 mr-md">
          <a-progress :percent="percent" />
        </div>
      </div>
      <div class="d-flex">
        <span class="w-100 mr-md text-right light">注意</span>
        <div class="light">
          <p>1.图片上传只支持bmp、png、jpeg、jpg、gif、x-icon格式</p>
          <p>2.图片最大不超过5M</p>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button @click="cancel" :loading="loading">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit()"
        >批量上传</a-button
      >
    </template>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, Ref, toRefs } from "vue";
import resourceApis from "@/apis/resource";
import { useStore } from "@/store";
import { dataURLtoFile, guid } from "@/utils/tools";
import { message } from "ant-design-vue";
import { uploadImage } from "@/utils/uploadOss";
import {
  CloseCircleFilled,
  DeleteOutlined,
  ScissorOutlined,
  EyeOutlined,
} from "@ant-design/icons-vue";
import { numDiv, numMul } from "@/utils/num";
import { UserActionTypes } from "@/store/modules/user/action-types";
import { stat } from "fs";

export default defineComponent({
  name: "OwnMultiPhotoUpload",
  props: {
    folders: {
      type: Array,
      request: true,
    },
  },
  components: {
    CloseCircleFilled,
    DeleteOutlined,
    ScissorOutlined,
    EyeOutlined,
  },
  setup(props, { emit }) {
    const store = useStore();
    const uploadInput = ref(null);
    const state = reactive({
      visible: false as boolean,
      needUpdate: false as boolean,
      folderId: undefined,
      type: "add",
      loading: false as boolean,
      fileList: [] as Array<any>,
      isUploadingFile: false as boolean,
      percent: 0 as number,
      canUploadImgType: [
        "image/jpeg",
        "image/jpg",
        "image/png",
        "image/gif",
        "image/x-icon",
      ],
      canUploadImgSize: 5,
      viewVisible: false,
      viewCurrent: 0,
    });

    const open = (folderId) => {
      state.folderId = folderId;
      state.fileList = [];
      state.visible = true;
      state.needUpdate = false;
      state.loading = false;
      state.isUploadingFile = false;
      state.percent = 0;
    };
    const setVisible = (value, i = 0): void => {
      state.viewVisible = value;
      state.viewCurrent = i;
    };

    // 选择图片
    const chooseFile = () => {
      (uploadInput as any).value.click();
    };
    // 选择图片回调
    const fileChangeEvent = (e) => {
      const file = e.srcElement.files; // 获取拿到的文件
      console.log(file);
      let msg = "";
      for (let i = 0, len = file.length; i < len; i++) {
        console.log(isAllowImgType(file[i].type), file[i].size / 1024 / 1024);
        if (
          !isAllowImgType(file[i].type) ||
          file[i].size / 1024 / 1024 > state.canUploadImgSize
        ) {
          msg = "已过滤不符合要求的文件";
        } else {
          const _type = file[i].name.split(".");
          let reader = new FileReader();
          reader.readAsDataURL(file[i]);
          reader.onload = (e: any) => {
            // console.log(_base64)
            state.fileList.push({
              fileType: file[i].type,
              type: _type[_type.length - 1],
              name: guid(),
              src: e.target.result,
            });
          };
        }
      }
      if (msg) {
        message.error(msg);
      }
    };

    // 判断是否是允许上次的文件格式
    const isAllowImgType = (imgtype: string) => {
      return state.canUploadImgType.includes(imgtype);
    };

    // 删除图片
    const deleteImg = (name: string) => {
      // state.fileList.splice(i, 1);
      state.fileList = state.fileList.filter((item) => item.name !== name);
    };

    // 裁剪图片
    const openCropped = (data: any, i: number) => {};

    const submit = async () => {
      try {
        if (state.fileList.length === 0)
          return message.error("请至少选择一张图片");
        // TODO 判断云库容量是否足够
        state.loading = true;
        const tokenRes: boolean = await store.dispatch(
          UserActionTypes.ACTION_OSS_TOKEN,
          null
        );
        if (!tokenRes) {
          state.loading = false;
          message.error("获取oss token失败，请刷新页面重试");
          return;
        }
        state.isUploadingFile = true;
        let uploadRes: unknown[] = [],
          step = numDiv(100, state.fileList.length, 2);
        const files = state.fileList.map((item) =>
          dataURLtoFile(item.src, `${guid()}.${item.type}`)
        );
        for (let i = 0; i < files.length; i++) {
          const res = await uploadImage(files[i]);
          state.percent = numMul(step, i, 2);
          if (res.success) {
            uploadRes.push(res.data);
          }
        }
        state.percent = 100;
        const saveRes: any = await resourceApis.createPhoto({
          list: uploadRes,
          folderId: state.folderId,
          companyId: store.state.user.company.id,
        });
        if (saveRes.code === 0) {
          state.needUpdate = true;
          cancel();
        }
      } catch (err) {
        state.loading = false;
      }
    };

    const cancel = () => {
      if (state.needUpdate) {
        emit("submit");
      }
      state.loading = false;
      state.visible = false;
    };
    return {
      open,
      uploadInput,
      chooseFile,
      fileChangeEvent,
      submit,
      cancel,
      deleteImg,
      setVisible,
      openCropped,
      ...toRefs(state),
    };
  },
});
</script>
<style lang="less" scoped>
.file-wrapper {
  margin-left: 120px;
  margin-bottom: 10px;
  border: 1px solid #f0f1f2;
  padding: 10px 0 0 10px;

  .image-box {
    width: 80px;
    height: 80px;
    margin: 0 10px 10px 0;
    display: inline-block;
    position: relative;

    img {
      width: 100%;
      height: 100%;
    }

    .delete {
      position: absolute;
      right: -5px;
      top: -10px;
      z-index: 5;

      i {
        color: red;
      }
    }
  }
}
</style>